﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using System.Windows.Controls;
using System.Collections.Specialized;
using System.Windows.Media;
using System.Windows;

namespace Dynamic_UI_Framework
{
    [Export(typeof(CanvasPanelAdapter))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class CanvasPanelAdapter : AdapterBase<IPanel, DesignerCanvas>
    {
        protected override void Adapt(IPanel codon, DesignerCanvas target)
        {
            Panel p = codon as Panel;
            p.Target = target;

            target.ContextMenu = new ContextMenu();
            foreach (var item in p.GetMenuItem())
            {
                target.ContextMenu.Items.Add(item);
            }

            p.Items.CollectionChanged += (s, e) =>
            {
                if (e.Action == NotifyCollectionChangedAction.Add)
                {
                    foreach (var n in e.NewItems)
                    {
                        target.Children.Add((n as IVisual).Target as FrameworkElement);
                    }
                }
                else if (e.Action == NotifyCollectionChangedAction.Remove)
                {
                    foreach (var n in e.OldItems)
                    {
                        target.Children.Remove((n as IVisual).Target as FrameworkElement);
                    }
                }
                else if (e.Action == NotifyCollectionChangedAction.Reset)
                {
                    target.Children.Clear();
                }
            };
        }


        protected override IPanel Create()
        {
            return new Panel();
        }
    }
}
